<template>
  <div class="passport-home">
    <h2>我的游戏护照</h2>

    <!-- 虚拟旅行通知 -->
    <div v-if="showTravelNotice" class="travel-notice" @click="showTravelDetails">
      <div class="notice-content">{{ travelNotice }}</div>
      <div class="notice-actions">
        <button @click.stop="handleCareForVisitor">照顾</button>
      </div>
    </div>
    
    <!-- 旅行记录 -->
    <div v-if="showTravelRecords" class="travel-records">
      <h3>旅行记录</h3>
      <div class="record-list">
        <div v-for="record in travelRecords" :key="record.id" class="record-item">
          <div class="record-location">{{ getLocationName(record.location) }}</div>
          <div class="record-status">{{ record.status }}</div>
          <div class="record-time">{{ formatTime(record.startTime) }}</div>
        </div>
      </div>
    </div>
    
    <!-- 总探索度 -->
    <div class="overall-progress">
      <h3>总探索度: {{ Math.round(totalProgress * 100) }}%</h3>
      <div class="progress-bar">
        <div class="progress" :style="{ width: `${totalProgress * 100}%` }"></div>
      </div>
    </div>

    <div class="passport-level">
      <div class="level-badge">Lv.{{ userLevel }}</div>
      <div class="progress-bar">
        <div class="progress" :style="{ width: `${progress * 100}%` }"/>
      </div>
      <div class="level-info">
        还需 {{ xpNeeded }} XP 升级到 Lv.{{ userLevel + 1 }}
      </div>
      <div class="perks">
        <h3>当前特权</h3>
        <ul>
          <li v-for="perk in currentPerks" :key="perk">{{ perk }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { PassportSystem } from './services/passport.js';
import { ProgressService } from '../points/services/progress-service.js';
import { getCurrentUserInfo } from '@/utils/auth';
import { TravelModel } from '../space/services/travel-model.js';

const userInfo = getCurrentUserInfo();
const userXP = ref(userInfo?.xp || 0); // 假设用户XP从用户信息中获取
const totalProgress = ref(0);
const gameProgress = ref({});

const userLevel = computed(() => PassportSystem.getUserLevel(userXP.value));
const progressData = computed(() => PassportSystem.getNextLevelProgress(userXP.value));
const progress = computed(() => progressData.value.progress);
const xpNeeded = computed(() => progressData.value.xpNeeded);
const currentPerks = computed(() => {
  const levelData = PassportSystem.LEVELS[userLevel.value - 1];
  return levelData ? levelData.perks : [];
});

// 虚拟旅行通知相关
const travelNotice = ref('');
const showTravelNotice = ref(false);
const showTravelRecords = ref(false);
const travelRecords = ref([]);
const currentTravelId = ref('');
let ws = null;

// 处理照顾访客
const handleCareForVisitor = async () => {
  if (!currentTravelId.value) return;
  
  try {
    await TravelModel.careForVisitor(userInfo.userId, currentTravelId.value);
    travelNotice.value = '已照顾访客，获得奖励!';
  } catch (error) {
    console.error('照顾访客失败:', error);
  }
};

// 显示旅行详情
const showTravelDetails = () => {
  showTravelRecords.value = !showTravelRecords.value;
};

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

// 获取地点名称
const getLocationName = (location) => {
  return TravelModel.getLocationName(location);
};

// 连接到WebSocket服务器
const connectWebSocket = () => {
  // 这里需要替换为实际的WebSocket服务器地址
  const wsUrl = `ws://localhost:9988/ws?userId=${userInfo.id}&userName=${encodeURIComponent(userInfo.name)}`;
  ws = new WebSocket(wsUrl);

  ws.onmessage = async (event) => {
    const message = JSON.parse(event.data);
    
    // 处理虚拟旅行通知消息
    if (message.type === 16) { // MessageTypeTravelNotice
      travelNotice.value = message.content;
      currentTravelId.value = message.travelId;
      showTravelNotice.value = true;
      
      // 更新旅行记录
      if (message.travelId) {
        try {
          const record = await TravelModel.getTravelRecord(message.travelId);
          travelRecords.value = [record, ...travelRecords.value].slice(0, 5);
        } catch (error) {
          console.error('获取旅行记录失败:', error);
        }
      }
      
      // 3秒后自动隐藏通知
      setTimeout(() => {
        showTravelNotice.value = false;
      }, 3000);
    }
  };

  ws.onclose = () => {
    // 连接关闭时尝试重连
    setTimeout(connectWebSocket, 3000);
  };
};

onMounted(async () => {
  connectWebSocket();
  
  // 加载游戏进度
  try {
    const progress = await ProgressService.getUserProgress(userInfo.userId);
    totalProgress.value = progress.totalProgress;
    gameProgress.value = progress.games;
  } catch (error) {
    console.error('加载游戏进度失败:', error);
  }
});

onUnmounted(() => {
  if (ws) {
    ws.close();
  }
});
</script>

<style scoped>
.passport-home {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.passport-level {
  background: #f5f5f5;
  border-radius: 10px;
  padding: 20px;
  margin-top: 20px;
}

.level-badge {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.progress-bar {
  height: 20px;
  background: #ddd;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress {
  height: 100%;
  background: #42b983;
  transition: width 0.3s ease;
}

.level-info {
  color: #666;
  margin-bottom: 15px;
}

.perks h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.perks ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.perks li {
  color: #666;
  padding: 5px 0;
}

/* 虚拟旅行通知样式 */
.travel-notice {
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 20px;
  color: #0d47a1;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  animation: fadeInOut 3s ease-in-out;
}

.travel-notice .notice-actions button {
  background: #42b983;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

/* 旅行记录样式 */
.travel-records {
  background: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 20px;
}

.travel-records .record-list {
  margin-top: 10px;
}

.travel-records .record-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.travel-records .record-item:last-child {
  border-bottom: none;
}

@keyframes fadeInOut {
  0% { opacity: 0; }
  10% { opacity: 1; }
  90% { opacity: 1; }
  100% { opacity: 0; }
}
</style>